import java.util.HashMap;

/**
 * 1234. 替换子串得到平衡字符串
 */
public class No1234 {
    public int balancedString(String s) {
        int left = 0, right = -1;
        int length = s.length();
        int avg = length / 4;
        int result = length;

        char[] charArray = s.toCharArray();
        HashMap<Character, Integer> hashMap = new HashMap<>();
        hashMap.put('Q', 0);
        hashMap.put('W', 0);
        hashMap.put('E', 0);
        hashMap.put('R', 0);

        // 初始化不替换内容字符出现次数数组，即初始滑动窗口维护一个空串
        for (char c : charArray) {
            hashMap.put(c, hashMap.get(c) + 1);
        }

        while (left < length) {
            if (hashMap.values().stream().allMatch(integer -> integer <= avg)) {
                result = Math.min(result, right - left + 1);
                hashMap.put(charArray[left], hashMap.get(charArray[left]) + 1);
                left++;
            } else {
                if (right == length - 1) {
                    break;
                }
                right++;
                hashMap.put(charArray[right], hashMap.get(charArray[right]) - 1);
            }
        }
        return result;
    }
}
